<?php
namespace app\common\service;

use app\common\helper\AipFaceHelper;
use app\common\util\Upload;
use app\common\util\Util;
use think\Request;
use think\Log;

class AipFaceService extends BaseService
{

    /**
     * 上传人脸头像并调用百度AI进行人脸检测
     * @param $sid
     * @param $uid
     * @param Request $request
     * @return array
     */
    public function uploadStudentAvatarAndCheck($sid, $uid, $media_id){
        /*//保存路径
        $save_path = ROOT_PATH . 'public' . DS . 'uploads'. DS . 'students_avatar' . DS . $uid;
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }

        $file = $request->file('file');
        $info  = $file->move($save_path);
        if(!$info){
            return ['status' => 0, 'msg' => '图片上传出错'];
        }

        //获取文件路径
        $img_path = $info->getPathname();*/

//        $media_id = 'wPjFkmVmlGSNlH0Fe0QCxX6miaOjEK--o6AOdUk7nwodOhriuWQJT7wUfv6v3A5S';

        $save_path = ROOT_PATH . 'public' . DS . 'uploads'. DS . 'students_avatar';
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }
        $file_name = 'avatar_'.$uid.'.jpg';

        $wxService = new WeixinService();
        $img_path = $wxService->get_stream($sid, $media_id, $save_path, $file_name);

        //调用百度AI人脸检测接口
        $ai = new AipFaceHelper();
        $r = $ai->detect($img_path);

        if($r['result_num'] == 0 || empty($r['result'])){
            return ['status' => 0, 'msg' => '未检测到人脸，请重新选择有效图片'];
        }
        $userInfo ='';
        $update = $ai->updateUser($uid, $userInfo, $sid,$img_path);
        Log::record('上传图片.1:'.json_encode($update));
        if(isset($update['error_code']))
        {
            $update = $ai->addUser($uid, $userInfo, $sid,$img_path);
            Log::record('上传图片.2:'.json_encode($update));
        }



        //将图片上传到七牛云
        $_FILES[0] = [
            'name' => $file_name,
            'type' => 'image/jpeg',
            'tmp_name' => $img_path,
            'size' => filesize($img_path)
        ];
        $qiniu = Upload::uploadFile();
        if($qiniu == false){
            return ['status'=> 0, 'msg'=>'上传失败', 'data' => ''];
        }
        $qiniu_img_url = Util::qiniu_url($qiniu);

//        //更新用户数据
//        $result = db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('avatar', $qiniu_img_url);

        return $qiniu_img_url ? ['status' => 1, 'msg' => '上传成功', 'data' => ['img_url' => $qiniu_img_url]] : ['status' => 0, 'msg' => '上传失败'];
    }


    /**
     * 保存学员人脸签到头像
     * @param $sid
     * @param $uid
     * @param $avatar
     * @return int
     */
    public function saveStudentAvatar($sid, $uid, $avatar){
        return db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('avatar', $avatar);
    }

    /**
     * 激活帐号并保存人脸签到头像
     * @param $sid
     * @param $uid
     * @param $mobile
     * @param $sms_code
     * @param $avatar
     * @return array
     */
    public function activeStudentsInfo($sid, $uid, $mobile, $sms_code, $avatar){
        $courseService = new CourseService();
        $bind_res = $courseService->bind_phone($sid, $uid, $mobile, $sms_code);
        if($bind_res['status'] == 0){
            return $bind_res;
        }
        $res = $this->saveStudentAvatar($sid, $uid, $avatar);
        if(!$res){
            return ['status' => 0, 'msg' => '保存失败'];
        } else {
            return ['status' => $bind_res['status'], 'msg' => '保存成功'];
        }
//        return $res ? ['status' => 1, 'msg' => '保存成功'] : ['status' => 0, 'msg' => '保存失败'];
    }


    /**
     * 获取课程、班级、学员列表信息
     * @param $face_sign_code
     * @return array
     */
    public function getCourseInfoByCode($face_sign_code){
        $course_filed = 'sid,courseid,name,speaker,schooltime,schoolovertime,description';
        $course_info = db('course')
                        ->field($course_filed)
                        ->where([
                            'face_sign_code' => $face_sign_code,
                            'schoolovertime' => ['>', time()],
                            'course_status' => 1
                        ])
                        ->find();
        if(!$course_info){
            return ['status' => 0, 'msg' => '课程信息不存在'];
        }
        $course_info['speaker'] = json_decode($course_info['speaker'], 1);
        $course_info['schooltime'] = date('Y-m-d H:i', $course_info['schooltime']);
        $course_info['schoolovertime'] = date('Y-m-d H:i', $course_info['schoolovertime']);

//        $relate_class_ids = db('course_class')->where(['courseid' => $course_info['courseid']])->column('classid');
        //获取课程关联的班级信息
        $relate_class_info = db('course_class cc')
                            ->field('cl.classid,cl.name')
                            ->join('course cr', 'cc.courseid=cr.courseid')
                            ->join('classes cl', 'cl.classid=cc.classid')
                            ->where(['cc.courseid' => $course_info['courseid']])
                            ->select();
        $relate_class_ids = []; //保存关联班级ID
        if($relate_class_info){
            foreach($relate_class_info as $k => $v){
                $relate_class_ids[$k] = $v['classid'];
            }
        }
        //保存本班学员用户ID
        $self_class_uids = [];
        if($relate_class_ids){
            $self_class_uids = db('class_students')->where(['classid' => ['in', $relate_class_ids], 'uid' => ['>', 0]])->column('uid');
            $self_class_uids = array_unique($self_class_uids);
        }

        //获取购买课程的学员
        $order_course_info = db('order_course oc')
                            ->field('oc.buyer_id')
                            ->join('order o', 'oc.order_id=o.order_id')
                            ->where(['oc.course_id' => $course_info['courseid'], 'o.status' => 1])
                            ->select();
        $order_course_uids = [];
        if($order_course_info){
            foreach($order_course_info as $key => $val){
                $order_course_uids[$key] = $val['buyer_id'];
            }
        }

        //获取学员列表
        $uids = array_unique(array_merge($self_class_uids, $order_course_uids));
        $student_field = 'id as student_id,uid,sid,name,phone,company,avatar';
        $student_list = db('students')->field($student_field)->where(['uid' => ['in', $uids]])->whereNotNull('avatar')->select();
        if($student_list){
            foreach($student_list as $ky => $vy){
                $student_list[$ky]['company'] = Util::unserializeStr($vy['company']);
            }
        }

        //获取店铺信息
        $store_info = db('store')->field('store_name,logo')->where(['store_id' => $course_info['sid']])->find();
        $data = [
            'course_info' => $course_info,
            'class_info' => $relate_class_info,
            'student_list' => $student_list,
            'store_info' => $store_info
        ];
        return ['status' => 1, 'data' => $data, 'msg' => '获取成功'];
    }


    /**
     * 人脸签到
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function faceSign($uid, $course_id, $type){
        //查询是否为本班学员
        $related_class_ids = db('course_class')->where(['courseid' => $course_id])->column('classid');
        $is_class_user = db('class_students')->where(['uid' => $uid, 'classid' => ['in', $related_class_ids]])->find();
        if(!$is_class_user){
            //查询是否为购买的学员
            $order_user = db('order_course oc')
                            ->join('order o', 'o.order_id=oc.order_id')
                            ->where(['oc.course_id' => $course_id, 'oc.buyer_id' => $uid, 'o.status' => 1])
                            ->find();
            if(!$order_user){
                return ['status' => 0, 'msg' => '请联系工作人员'];
            }
        }

        //查询头像是否为空
        $student = db('students')->field('id,sid,avatar')->where(['uid' => $uid])->find();
        if(empty($student)){
            return ['status' => 0, 'msg' => '用户未激活'];
        }
        //人脸签到需要头像资料对比;二维码核验签到则无需
        if($type == 1){
            if(empty($student['avatar'])){
                return ['status' => 0, 'msg' => '头像资料未完善'];
            }
        }

        $course_students = db('course_students')->where(['uid' => $uid, 'courseid' => $course_id])->find();

        if($course_students){
            if($course_students['sign_status'] == 0){
                $r = db('course_students')->where(['uid' => $uid, 'courseid' => $course_id])->setField('sign_status', 1);
            } else {
                return ['status' => 1, 'msg' => '您已签到'];
            }
        } else {
            $insert_data = [
                'courseid' => $course_id,
                'uid' => $uid,
                'sid' => $student['sid'],
                'sign_status' => 1,
                'sign_type' => $type == 1 ? 2 : 3,  //签到类型(1:扫码签到;2:人脸签到;3:二维码核验签到)
                'addtime' => time(),
                'formal_status' => 1,
                'ourclass_status' => $is_class_user ? 1 : 0,
                'studentsid' => $student['id']
            ];

            $r = db('course_students')->insert($insert_data);
        }

        $wxTplService = new WxTplMsgService();
        $course_info = db('course')->where(['courseid' => $course_id])->find();
        if($r){
            //发送模版消息
            $wxTplService->send($student['sid'], $uid, 'sign_success', $course_info);
            return ['status' => 1, 'msg' => '签到成功!'];
        } else {
            return ['status' => 0, 'msg' => '签到失败!'];
        }
    }
}







